package org.nood.iptv.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.nood.iptv.R;
import org.nood.iptv.adapter.ChannelListAdapter;
import org.nood.iptv.entity.ChannelResult;
import org.nood.iptv.utils.Contants;
import org.nood.iptv.utils.JsonUtils;
import org.nood.iptv.utils.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Noodlewar
 * @date 2017/11/23
 */
public class ChannelFragment extends Fragment {

    private Context context;

    @BindView(R.id.channel_view)
    ListView channelView;
    @BindView(R.id.channel_no_list)
    View channelNoList;
    @BindView(R.id.channel_loading)
    View channelLoading;

    private ChannelListAdapter channelListAdapter;

    private int position;

    private List<ChannelResult> channelResults;

    public static ChannelFragment newInstance(int position) {
        Bundle args = new Bundle();
        args.putInt("position", position);
        ChannelFragment fragment = new ChannelFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.channel_pager, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        int positionIndex = getArguments().getInt("position");

        this.context = view.getContext();
        getData(positionIndex);
    }

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            ChannelResult channelResult = channelResults.get(position);
            listener.onChannelSelected(channelResult.getPlayURL());
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (channelResults != null && channelResults.size() > 0) {
                //有数据
                //设置适配器
                channelListAdapter = new ChannelListAdapter(context, channelResults);
                channelView.setOnItemClickListener(new MyOnItemClickListener());
                channelView.setAdapter(channelListAdapter);
                channelNoList.setVisibility(View.GONE);
            } else {
                //没有数据
                //文本显示
                channelNoList.setVisibility(View.VISIBLE);
            }
            //ProgressBar隐藏
            channelLoading.setVisibility(View.GONE);
        }
    };


    /**
     * 使用okgo的get请求网络文本数据
     */
    public void getData(final int positionIndex) {
        LogUtils.e("节目表数据初始化");

        String url = Contants.BASE_URL + "client/channel/category";
        OkGo.<String>get(url).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String data = response.body();
                LogUtils.i(data);
                String json = JsonUtils.channelResultResolver(data, positionIndex);
                channelResults = JSON.parseArray(json, ChannelResult.class);
                handler.sendEmptyMessage(10);
            }
        });
    }

    private OnChannelSelectedListener listener;

    public interface OnChannelSelectedListener {
        /**
         * 选取频道时触发的事件·
         *
         * @param url
         */
        void onChannelSelected(String url);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            listener = (OnChannelSelectedListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + "must implement OnScheduleSelectedListener");
        }
    }

}
